package com.mvc.utils;

import java.beans.PropertyDescriptor;
import java.io.File;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.imageio.stream.FileImageOutputStream;

import org.apache.commons.beanutils.PropertyUtilsBean;
import org.huangqj.consant.ValidatorUtil;

import com.mvc.framework.constant.GlobalConstant;

public class StringUtil {

	/**
	 * 格式化字符串
	 * 
	 * 例：formateString("xxx{0}bbb",1) = xxx1bbb
	 * 
	 * @param str
	 * @param params
	 * @return
	 */
	public static String formateString(String str, String... params) {
		for (int i = 0; i < params.length; i++) {
			str = str.replace("{" + i + "}", params[i] == null ? "" : params[i]);
		}
		return str;
	}
	  /**
     * @author qingjie
     * 传入时间和跳跃的月份数，获取下一次时间
     * @param date
     * @param amount
     * @return
     * Date:2015-11-08 18:31
     */
    public static String getNextTime(String date, Integer amount){
    	Calendar calendar = Calendar.getInstance();
    	try {
			Date nowDate = GlobalConstant.sdf.parse(date);
			calendar.setTime(nowDate);
			if(amount>12){
				calendar.add(Calendar.DAY_OF_MONTH, amount);
			}else calendar.add(Calendar.MONTH, amount);
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	return GlobalConstant.sdf.format(calendar.getTime());
    }
	/**
	 * 字符串部分字符替换
	 * @author qingjie
	 * @param value 要转换的值
	 * @param type 转换的样子
	 * @param start 转换开始位置
	 * @param end 转换结束为止
	 * @return
	 */
	public static String replaceNumberToString(String value,String type,int start,int end){
		StringBuffer sb = new StringBuffer();
		if(value!=null){
			int i = 0;
			char[] ch = value.toCharArray();
			for(char c : ch){
				if(i>=start && i< end){
					sb.append(type);
				}else sb.append(c);
				i++;
			}
		}
		return sb.toString();
	}

	/**
	 * @author qingjie
	 * 字符串补位
	 * @param w 补位数
	 * @param v 补位值
	 * @return
	 */
	public static String formatString(Integer w, Integer v){
		return  String.format("%"+w+"d", v).replace(" ", "0");
	}
	
	/**
	 * 获取4位随机数
	 * @author qingjie
	 * @return
	 */
	public static String getRandom(){
		Random random = new Random();
		StringBuffer randomCode=new StringBuffer();
		//获取6位随机数
		for(int i=0;i<6;i++){
			randomCode.append(String.valueOf(random.nextInt(10)));
		}
		//获取验证码
		return randomCode.toString();
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(replaceNumberToString("450702198811149011",".",6,14));
	}
	
	
	/**
     * @author qingjie
     * 根据参数自动拼接hql
     * @param params
     * @param tname
     * @return
     */
    public static String getHql(String tname,Map<String, Object> params,String order){
    	String hql = " from " + tname + " t where 1=1";
    	for (Map.Entry<String, Object> map : params.entrySet()) {
			hql+=" and t."+ map.getKey() + "= :" + map.getKey();
		}
    	hql+= " order by t.id "+ order;
    	return hql;
    }
    
    /**
     * @author
     * 根据参数自动拼接hql
     * @param params
     * @param tname
     * @return
     */
    public static String getHql2(String tname,Map<String, Object> params){
    	String hql = " from " + tname + " t where 1=1";
    	for (Map.Entry<String, Object> map : params.entrySet()) {
			hql+=" and t."+ map.getKey() + "= :" + map.getKey();
		}
    	return hql;
    }
    
	/**
	 * @author Roy
	 * 根据birthday ,获取年龄
	 * @param birthday
	 * @return
	 */
	 public static Integer getAge(String birthday){
	    	Integer age = 0;
	    	try {
				Date birDate = GlobalConstant.SDF2.parse(birthday);
				age = ((int) ((GlobalConstant.DATE.getTime() - birDate.getTime())/(24 *60 *60 *1000) + 1)) / 365;
			} catch (Exception e) {
				e.printStackTrace();
			}
	    	return age;
	    }
	 
		
	 public static String getCr(double pl){
	    	String cr = "";
			if(pl<60){
				cr = "较差";
			}else if(pl<=70){
				cr = "一般";
			}else if(pl<=80){
				cr = "较好";
			}else cr = "很好";
			return cr;
		}
	 
	//将javabean实体类转为map类型，然后返回一个map类型的值
    public static Map<String, Object> beanToMap(Object obj) { 
            Map<String, Object> params = new HashMap<String, Object>(0); 
            try { 
                PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean(); 
                PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj); 
                for (int i = 0; i < descriptors.length; i++) { 
                    String name = descriptors[i].getName(); 
                    if (!"class".equals(name)) { 
                    	if(!ValidatorUtil.isBlankOnString((String)propertyUtilsBean.getNestedProperty(obj, name))){
                    		params.put(name, propertyUtilsBean.getNestedProperty(obj, name)); 
                    	}
                    } 
                } 
            }catch (Exception e) { 
                e.printStackTrace(); 
            } 
            return params; 
    }
    
    public static boolean byte2Image(byte[] data,String path){
    	boolean b = false;
    	if(data.length<3||ValidatorUtil.isBlankOnString(path)) return b;
    	try {
    		//打开输入流
			FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
			//将byte写入硬盘
			imageOutput.write(data,0,data.length);
			imageOutput.close();
			b=true;
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return b;
    }
    
    /**
     * @author weiqian
     * 体质判断 体型
     * @param bmi
     * @return
     */
  	public static String weightState(Double bmi) {
		if (bmi < 18.5) {
			return "0";
		}else if (bmi<24) {
			return "1";
		}else if (bmi < 25) {
			return "2";
		}else if (bmi<28) {
			return "2";
		}else if (bmi < 29) {
			return "2";
		}else if (bmi < 40) {
			return "2";
		}else{
			return "2";
		}
	}
  	
  	 /**
     * @author qingjie
     * 血压状态
     * @param sbp 收缩压
     * @param dbp 舒张压
     * @return
     */
    public static String pressureState(double sbp,double dbp){
    	String pressure_state = "1";//1:正常血压,2:正常高值血压,3:轻度高血压,4:中度高血压,5:重度高血压
    	/**血压状态      判断依据：
	    	正常血压：收缩压:＜120 且 舒张压:＜80；
	    	正常高值血压:收缩压:120-139和(或)舒张压:80-89
	    	高血压：收缩压:≥140 和(或) 舒张压:≥90；
	    	轻度高血压:收缩压:140-159和(或)舒张压:90～99；
	    	中度高血压:收缩压:160-179和(或)舒张压:100-109
	    	重度高血压：收缩压:≥180 和（或）舒张压≥110；
    	*/
    	//先判断收缩压
    	if(sbp<120){//正常血压
    		pressure_state = "1";
    	}else if(sbp<=139){//正常高值血压
    		pressure_state = "2";
    	}else{//高血压
    		if(sbp<=159){//轻度高血压
    			pressure_state = "3";
    		}else if(sbp<=179){//中度高血压
    			pressure_state = "4";
    		}else pressure_state = "5";//重度高血压
    	}
    	//再判断舒张压
    	if(dbp<80&&pressure_state=="1"){//正常血压
    		pressure_state = "1";
    	}else if(dbp<=89&&(pressure_state=="1"||pressure_state=="2")){//正常高值血压
    		pressure_state = "2";
    	}else{//高血压
    		if(dbp<=99&&(pressure_state=="1"||pressure_state=="2"||pressure_state=="3")){//轻度高血压
    			pressure_state = "3";
    		}else if(dbp<=109&&pressure_state!="5"){//中度高血压
    			pressure_state = "4";
    		}else pressure_state = "5";//重度高血压
    	}
    	
    	return pressure_state;
    }
    
}
